package shun.demo.remote.touch.client;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import shun.demo.R;
import shun.demo.remote.touch.model.MyMotionEvent;

import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * Created by chen on 14-4-26.
 */
public class TouchClientActivity extends Activity implements View.OnClickListener {

    private InputClient mInputClient;
    private ObjectOutputStream mObjectOutputStream;
    private EditText mAddressText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_client);
        mAddressText = (EditText) findViewById(R.id.address);
        mInputClient = new InputClient();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        MyMotionEvent myMotionEvent = new MyMotionEvent();
        myMotionEvent.fromMotionEvent(ev);
        try {
            if (mObjectOutputStream != null) {
                mObjectOutputStream.writeObject(myMotionEvent);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(ev);
    }

    private class ConnectTask extends AsyncTask<String, Void, ObjectOutputStream> {

        private ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(TouchClientActivity.this);
            mProgressDialog.show();
        }

        @Override
        protected ObjectOutputStream doInBackground(String... params) {
            ObjectOutputStream oos = mInputClient.connect(params[0]);
            return oos;
        }

        @Override
        protected void onPostExecute(ObjectOutputStream oos) {
            if (mProgressDialog.isShowing()) {
                try {
                    mProgressDialog.dismiss();
                } catch (Exception e) {
                }
            }
            String text = null;
            if (oos != null) {
                mObjectOutputStream = oos;
                text = "Connect success";
            } else {
                text = "Connect failed";
            }
            Toast.makeText(TouchClientActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.connect:
                String string = mAddressText.getText().toString().trim();
                new ConnectTask().execute(string);
                break;
        }
    }
}
